package com.meng.spike.service.impl;

import com.meng.spike.entity.GoodsStore;
import com.meng.spike.repository.GoodsStoreRespository;
import com.meng.spike.service.GoodsStoreService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsStoreServiceImpl implements GoodsStoreService {

    @Resource
    private GoodsStoreRespository goodsStoreRespository;


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "del")
    private DefaultRedisScript<Boolean>  redisScriptDel;




    /**
     * 超时时间 5s
     */
    private static final int TIMEOUT = 5*1000;

    /**
     * 根据产品编号更新库存
     * @param code
     * @return
     */
    @Override
    public String updateGoodsStore(String code,int count) {
        //上锁,用UUID作为特殊标识
        String clientID = UUID.randomUUID().toString();
        try{
            //设置value值为我们生存的clientID
            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(code,clientID,10,TimeUnit.SECONDS);
            if (!result){
                //获取锁失败的操作
                return "排队人数太多，请稍后再试.";
            }

            //具体业务逻辑...
            GoodsStore goodsStore = getGoodsStore(code);
            if(goodsStore != null){
                if(goodsStore.getStore() <= 0){
                    return "对不起，卖完了";
                }
                if(goodsStore.getStore() < count){
                    return "对不起，库存不足，库存为："+goodsStore.getStore()+" 您的购买数量为："+count;
                }
                System.out.println("剩余库存："+goodsStore.getStore());
                System.out.println("扣除库存："+count);
                int i = goodsStoreRespository.updateStore(code, count);
                if(i>=0){
                    return "恭喜您，购买成功！";
                }else {
                    return "购买失败";
                }
            }else {
                    return "获取库存失败";
            }
        }finally {
            //lua脚本保证原子性
            List<String> keys = Arrays.asList(code);
            stringRedisTemplate.execute(redisScriptDel, keys, clientID);
        }

    }

    /**
     * 获取库存对象
     * @param code
     * @return
     */
    @Override
    public GoodsStore getGoodsStore(String code){
        Optional<GoodsStore> optional = goodsStoreRespository.findById(code);
        return optional.get();
    }
}
